package com.yankaizhang.blog.config;

import com.yankaizhang.blog.security.CustomAuthenticationFailureHandler;
import com.yankaizhang.blog.security.CustomAuthenticationSuccessHandler;
import com.yankaizhang.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * spring-security配置类
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    DataSource dataSource;

    @Autowired
    UserService userService;

    @Autowired
    CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;


    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(13);
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userService); // 将实现了userDetails接⼝的userService加⼊auth
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 开启同源iframe许可
        http.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable();

        http.authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/index", "/", "/archive/**", "/post/**", "/tags/**", "/about", "/toLogin").permitAll()
                .antMatchers("/admin", "/admin/**").hasRole("ADMIN");

        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/toLogin")
                .loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/admin/index") // 登录成功后的⻚⾯
                // 登录成功
                .successHandler(customAuthenticationSuccessHandler)
                // 登录失败
                .failureHandler(customAuthenticationFailureHandler)
                .and()
                .rememberMe()                                   // 记住我配置
                    .tokenRepository(persistentTokenRepository())  // 配置数据库源
                    .tokenValiditySeconds(3600)
                    .userDetailsService(userService)
                .and()
                // 登出
                .logout()
                    .logoutUrl("/logout")
                    .clearAuthentication(true)
                    .invalidateHttpSession(true)
    //                .logoutSuccessHandler(customLogoutSuccessHandler)
                    .logoutSuccessUrl("/index")
                    .permitAll()
                .and()
                .csrf().disable();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl persistentTokenRepository = new JdbcTokenRepositoryImpl();
        // 将 DataSource 设置到 PersistentTokenRepository
        persistentTokenRepository.setDataSource(dataSource);
        // 第一次启动的时候自动建表（可以不用这句话，自己手动建表，源码中有语句的）
//        persistentTokenRepository.setCreateTableOnStartup(true);
        return persistentTokenRepository;
    }
}